/**
 * @Date: 2022-03-10 20:07:43
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-03-13 16:56:47
 * @FilePath: \zhihuReal\controllers\questionCtl.js
 * @Description: 问题控制器
 */
const {
    SuccessModel,
    ErrorModel
} = require('../res-model/index')
const Question = require('../model/questionMdl')
const User = require('../model/usersMdl')

//获取问题列表
const questionList = async (ctx) => {
    //分页
    const {
        limit = 10, page = 1
    } = ctx.query
    const pagenum = Math.max(+page, 1) - 1
    const limitnum = Math.max(+limit, 1)
    //模糊搜索
    let q = new RegExp(ctx.query.keyword)
    const list = await Question.find({
        //多命中
        $or: [{
            name: q
        }, {
            title: q
        }]
    }).limit(limitnum).skip(pagenum * limitnum)
    ctx.body = new SuccessModel(list)
}
//获取单个问题
const oneQuestion = async (ctx) => {
    const {
        fields = ''
    } = ctx.query
    const selectFields = fields.split(';').filter(f => f).map(f => ' +' + f).join('')
    const question = await Question.findById(ctx.params.id).select(selectFields).populate('questioner topics')
    if (!question) {
        ctx.throw(404, '问题不存在')
    } else {
        ctx.body = new SuccessModel(question)
    }
}
//创建问题
const createQuestion = async (ctx) => {
    ctx.verifyParams({
        title: {
            type: 'string',
            required: true
        },
        desc: {
            type: 'string',
            required: false
        },
    })
    const newQuestion = await Question.create({
        ...ctx.request.body,
        questioner: ctx.state.user._id
    })

    ctx.body = new SuccessModel()
}
//更新问题
const updateQuestion = async (ctx) => {
    ctx.verifyParams({
        title: {
            type: 'string',
            required: false
        },
        desc: {
            type: 'string',
            required: false
        },
    })
    const newQuestion = await Question.findByIdAndUpdate(ctx.params.id, ctx.request.body)
    ctx.body = new SuccessModel(newQuestion)
}
//删除问题
const removeQuestion = async (ctx) => {
    const question = await Question.findByIdAndRemove(ctx.params.id)
    if (!question) {
        ctx.throw(404, '你要删除的问题不存在')
    }
    ctx.status = 204

}

module.exports = {
    questionList,
    oneQuestion,
    createQuestion,
    updateQuestion,
    removeQuestion,
}